package cn.hpclub.server.controller.h5.campus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.net.MediaType;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.constant.H5ApiConstant;
import cn.hpclub.server.controller.h5.BaseH5Controller;
import cn.hpclub.server.model.Broadband;
import cn.hpclub.server.model.MemberOrg;
import cn.hpclub.server.model.ServiceReservation;
import cn.hpclub.server.util.DESAS;
import cn.hpclub.server.util.HttpUtil;
import cn.hpclub.server.util.SystemConfigUtil;

public class CampusBroadbandH5Controller extends BaseH5Controller{
    private static final Logger logger           = LoggerFactory.getLogger(CampusBroadbandH5Controller.class);
    private String              CMCC_HOST_PREFIX = SystemConfigUtil.getSystemConfig().getCmccHostPrefix();
    private String              REST_HOST_PREFIX = SystemConfigUtil.getSystemConfig().getRestHostPrefix();

    /**
     * 验证是否实名认证
     * 
     * @Title: custRealChk
     * @Description:TODO void
     */
    public void custRealChk(){
        String result = getCustRealChkResult();

        renderJson(result);
    }

    /**
     * 获取验证码
     * 
     * @Title: getVerifyCode
     * @Description:TODO void
     */
    public void getVerifyCode(){
        String result = getVerifyCodeResult();

        renderJson(result);
    }

    /**
     * 保存订单
     * 
     * @Title: saveOrder
     * @Description:TODO void
     */
    public void saveOrder(){
        // String result = "";
        JSONObject o = null;
        JSONObject objResult = new JSONObject();
        String saveType = getPara(H5ApiConstant.Ui.SAVETYPE);
        if("1".equals(saveType)){// 1为保存订单,0为保存反馈信息
            // 1. 验证验证码
            String verifyCodeResult = getValidVerifyCodeResult();
            if(StrKit.notBlank(verifyCodeResult)){
                o = new JSONObject(verifyCodeResult);
                if(H5ApiConstant.ResultCode.SUCCESS_CODE == o.getLong("ResultCode")){
                    // 2. 验证是否实名认证
                    String custRealChkResult = getCustRealChkResult();
                    if(StrKit.notBlank(custRealChkResult)){
                        o = new JSONObject(custRealChkResult);
                        o = o.getJSONObject(H5ApiConstant.CmccKey.ROOT);

                        if(H5ApiConstant.CmccResultCode.RETURN_SUCCESS_CODE == (o
                                .getInt(H5ApiConstant.CmccKey.RETURN_CODE))
                                && "Y".equals(o.getJSONObject(H5ApiConstant.CmccKey.OUT_DATA)
                                .getString(H5ApiConstant.CmccKey.REAL_FLAG))){
                            long preAccept = Long.parseLong(getPreAccept());
                            logger.info("****saveOrder order_id = " + preAccept);
                            // 3.保存订单到本地数据库
                            if(saveOrderToLocal(preAccept)){
                                // 4.保存订单到移动
                                String saveOrderResult = getSaveOrderResult(preAccept);
                                logger.debug("****saveBroadBandOrder :: dpr result = " + saveOrderResult);
                                // test success
                                // saveOrderResult =
                                // "{\"ROOT\":{\"RETURN_CODE\":0,\"RETURN_MSG\":\"ok!\",\"USER_MSG\":\"处理成功!\",\"DETAIL_MSG\":\"OK!\",\"PROMPT_MSG\":\"\",\"OUT_DATA\":{\"PRE_ACCEPT\":201607061133202130}}}";

                                // test fail
                                // saveOrderResult =
                                // "{\"ROOT\":{\"RETURN_CODE\":302012899,\"RETURN_MSG\":\"数据库错误，请联系系统管理员！
                                // ERRID:35321920\",\"USER_MSG\":\"数据库错误，请联系系统管理员！\",\"DETAIL_MSG\":\"DBERR
                                // of sBroadPreChg, 3 errid:
                                // 1467771920\",\"PROMPT_MSG\":\"\"}}";

                                if(StrKit.notBlank(saveOrderResult)){
                                    o = new JSONObject(saveOrderResult);


                                    if(H5ApiConstant.CmccResultCode.SUCCESS_CODE
                                            .equals(o.getString(H5ApiConstant.CmccKey.RESCODE))){
                                        // 5.更新本地订单boss_no
                                        if(ServiceReservation.dao.updateGovBdOrder(
                                                                                   o.getJSONObject(H5ApiConstant.CmccKey.OUTDATA)
                                                                                           .getLong(H5ApiConstant.CmccKey.PRE_ACCEPT),
                                                                                   preAccept)){

                                            objResult.put(H5ApiConstant.CmccKey.RESCODE,
                                                          o.getString(H5ApiConstant.CmccKey.RESCODE));
                                        } else{
                                            logger.error("update local boss_no failed!!!！");
                                            objResult.put(H5ApiConstant.CmccKey.RESCODE,
                                                          H5ApiConstant.ResultCode.EXCEPTION_CODE);
                                            objResult.put(H5ApiConstant.CmccKey.RESMSG,
                                                          H5ApiConstant.Msg.SERVER_EXCEPTION);
                                        }

                                    } else{
                                        logger.error("save to DPR failed!!!！");
                                        objResult.put(H5ApiConstant.CmccKey.RESCODE,
                                                      o.getString(H5ApiConstant.CmccKey.RESCODE));
                                        objResult.put(H5ApiConstant.CmccKey.RESMSG,
                                                      o.getString(H5ApiConstant.CmccKey.RESMSG));
                                    }

                                } else{
                                    logger.error("save to DPR exception!!!！");
                                    objResult.put(H5ApiConstant.CmccKey.RESCODE,
                                                  H5ApiConstant.ResultCode.EXCEPTION_CODE);
                                    objResult.put(H5ApiConstant.CmccKey.RESMSG,
                                                  H5ApiConstant.Msg.SAVE_BROADBAND_DPR_EXCEPTION);

                                    // result = objResult.toString();
                                }
                            } else{
                                logger.error("save to local failed!!!！");
                                objResult.put(H5ApiConstant.CmccKey.RESCODE, H5ApiConstant.ResultCode.FAIL_CODE);
                                objResult.put(H5ApiConstant.CmccKey.RESMSG,
                                              H5ApiConstant.Msg.SAVE_BROADBAND_LOCAL_FAIL);

                                // result = objResult.toString();
                            }
                        } else{
                            logger.error("DPR custRealChk failed!!!！");
                            // result = o.toString();
                            objResult.put(H5ApiConstant.CmccKey.RESCODE, o.getInt(H5ApiConstant.CmccKey.RESCODE));
                            objResult.put(H5ApiConstant.CmccKey.RESMSG, o.getString(H5ApiConstant.CmccKey.RESMSG));

                            // result = objResult.toString();
                        }
                    } else{
                        logger.error("DPR custRealChk Exception!!!！");
                        objResult.put(H5ApiConstant.CmccKey.RESCODE, H5ApiConstant.ResultCode.EXCEPTION_CODE);
                        objResult.put(H5ApiConstant.CmccKey.RESMSG, H5ApiConstant.Msg.CUSTREALCHK_EXCEPTION);

                        // result = objResult.toString();
                    }
                } else{
                    logger.error("DPR verifyCode failed!!!！");
                    objResult.put(H5ApiConstant.CmccKey.RESCODE, o.getInt("ResultCode"));
                    objResult.put(H5ApiConstant.CmccKey.RESMSG, o.getString("Message"));
                }
            } else{
                logger.error("DPR verifyCode Exception!!!！");
                objResult.put(H5ApiConstant.CmccKey.RESCODE, H5ApiConstant.ResultCode.EXCEPTION_CODE);
                objResult.put(H5ApiConstant.CmccKey.RESMSG, H5ApiConstant.Msg.CAPTCHA_TOKEN_EXCEPTION);

                // result = objResult.toString();
            }

        } else{
            // 保存反馈信息到本地数据库
            long time = 0;
            if(saveOrderToLocal(time)){
                objResult.put(H5ApiConstant.CmccKey.RESCODE, H5ApiConstant.ResultCode.SUCCESS_CODE);
                objResult.put(H5ApiConstant.CmccKey.RESMSG, H5ApiConstant.Msg.SAVE_FEEDBACK_SUCCESS);

                // result = objResult.toString();
            } else{
                logger.error("save feedback to local failed!!!！");
                objResult.put(H5ApiConstant.CmccKey.RESCODE, H5ApiConstant.ResultCode.FAIL_CODE);
                objResult.put(H5ApiConstant.CmccKey.RESMSG, H5ApiConstant.Msg.SAVE_FEEDBACK_FAIL);

                // result = objResult.toString();
            }
        }

        renderJson(objResult.toString());
    }

    /**
     * 查询宽带预约订单数据列表
     */
    public void orderList(){
        JSONObject returnObj = setResponseObj(H5ApiConstant.ResultCode.FAIL_CODE, H5ApiConstant.Msg.FAIL, null);
        try{
            int pageNumber = getParaToInt(H5ApiConstant.Ui.PAGE_NUMBER, 1);
            int pageSize = getParaToInt(H5ApiConstant.Ui.PAGE_SIZE, 3);
            int userId = getParaToInt(H5ApiConstant.Ui.USERID);// 店员userId
            String keyword = getPara(H5ApiConstant.Ui.KEYWORD, "");// 订单号/客户手机号/客户姓名
            Page<Record> pager = ServiceReservation.dao.getBroadbandOrderList(pageNumber, pageSize, userId, keyword);

            dynBdOrderStatus(pager.getList());

            returnObj = setResponseObj(H5ApiConstant.ResultCode.SUCCESS_CODE, H5ApiConstant.Msg.EMPTY,
                                       JsonKit.toJson(pager));
        }
        catch(Exception e){
            returnObj = setResponseObj(H5ApiConstant.ResultCode.EXCEPTION_CODE, H5ApiConstant.Msg.EXCEPTION, null);
            e.printStackTrace();
        }

        renderText(returnObj.toString());
    }

    /**
     * @Title: dynBdOrderStatus
     * @Description:同步状态
     * @param list
     *            void
     * @throws Exception
     */
    private void dynBdOrderStatus(List<Record> list) throws Exception{
        String result = "";
        JSONObject o = null;
        JSONObject rtJo = null;
        for(Record r : list){
            boolean isReturnSuccess = false;
            result = getDynBdOrderStatusResult(r);
            logger.warn("getBroadBandOrderList :: rzl result = " + result);
            if(StrKit.notBlank(result)){
                o = new JSONObject(result);
                if(0 == o.getJSONObject("ROOT").getLong("RETURN_CODE")){
                    if(o.getJSONObject("ROOT").getJSONObject("OUT_DATA").has(H5ApiConstant.CmccKey.ROW)){
                        rtJo = o.getJSONObject("ROOT").getJSONObject("OUT_DATA")
                                .getJSONObject(H5ApiConstant.CmccKey.ROW);
                    }
                    if(rtJo != null){
                        isReturnSuccess = true;
                        // 宽带状态：PHONE_NO为0时，宽带还未开通，不为0时，宽带开通，且返回的值为宽带的号码
                        if("0".equals(rtJo.get(H5ApiConstant.CmccKey.PHONE_NO))){
                            r.set("rzl_order_status", "宽带还未开通");
                        } else{
                            r.set("rzl_order_status", "宽带已开通");
                            r.set("rzl_order_status_value", "null".equals(rtJo.get(H5ApiConstant.CmccKey.PHONE_NO)) ? ""
                                    : rtJo.get(H5ApiConstant.CmccKey.PHONE_NO));
                        }
                        // 订单状态
                        r.set("rzl_bd_status", "null".equals(rtJo.get(H5ApiConstant.CmccKey.STATE)) ? ""
                                : rtJo.get(H5ApiConstant.CmccKey.STATE));
                        // 小区名称
                        r.set("rzl_bd_address", "null".equals(rtJo.get(H5ApiConstant.CmccKey.COMM_NAME)) ? ""
                                : rtJo.get(H5ApiConstant.CmccKey.COMM_NAME));
                        // 归属区县
                        r.set("rzl_bd_area", "null".equals(rtJo.get(H5ApiConstant.CmccKey.DISTRICT_NAME)) ? ""
                                : rtJo.get(H5ApiConstant.CmccKey.DISTRICT_NAME));
                        // 订单号
                        r.set("rzl_bd_order_no", "null".equals(rtJo.get(H5ApiConstant.CmccKey.PRE_ACCEPT)) ? ""
                                : rtJo.get(H5ApiConstant.CmccKey.PRE_ACCEPT));
                    }
                    // }
                }
            }

            if(!isReturnSuccess){
                r.set("rzl_order_status", "");
                r.set("rzl_order_status_value", "");
                r.set("rzl_bd_status", "");
                r.set("rzl_bd_address", "");
                r.set("rzl_bd_area", "");
                r.set("rzl_bd_order_no", "");
            }
        }
    }

    /**
     * @Title: getDynBdOrderStatusResult
     * @Description:TODO
     * @param r
     * @return String
     * @throws Exception
     */
    private String getDynBdOrderStatusResult(Record r) throws Exception{
        /*
         * String encodeParams = encodeParams(getDynBdOrderStatusParams(1,
         * r.getStr(ServiceReservation.BOSS_NO))); logger.debug(
         * "encodeParams = " + encodeParams); HashMap<String, Object> hm = new
         * HashMap<String, Object>(); JSONObject o = new
         * JSONObject(encodeParams); hm.put(H5ApiConstant.CmccKey.RAWSTR,
         * o.get(H5ApiConstant.CmccKey.RAWSTR));
         * 
         * return HttpUtil.getHttpByPost(CMCC_HOST_PREFIX +
         * Constant.Url.GET_BD_ORDER, hm);
         */
        String phoneNo = r.getStr("clerk_mobile");
        JSONObject job = new JSONObject("{\"BODY\":{\"SVC_NAME\":\"d14550002\"}}");
        job.getJSONObject("BODY").put("PHONE_NO", phoneNo).put("PRE_ACCEPT", r.getStr(ServiceReservation.BOSS_NO))
                .put("CONTACT_PHONE", phoneNo);

        String restHostPrefix = SystemConfigUtil.getSystemConfig().getRestHostPrefix();
        String result = HttpUtil.syncPostJsonBody(restHostPrefix + Constant.RestUrl.GET_BD_ORDER, MediaType.JSON_UTF_8,
                                                  job.toString(), 30000);
        return result;
    }

    /**
     * @Title: getDynBdOrderStatusParams
     * @Description:TODO
     * @param
     * @param
     * @return HashMap<String,Object>
     */
    private HashMap<String, Object> getDynBdOrderStatusParams(int type, String param){
        String value = "type=" + type;
        if(type == 1){
            value += "|pre_accept=";
        } else if(type == 2){
            value += "|contact_phone=";
        } else if(type == 3){
            value += "|contact_name=";
        }
        value += param;
        HashMap<String, Object> hm = new HashMap<String, Object>();
        hm.put(H5ApiConstant.CmccKey.RAWSTR, value);

        return hm;
    }

    /**
     * @Title: getVerifyCodeResult
     * @Description:获取发送验证码接口的结果
     * @return String
     */
    private String getVerifyCodeResult(){
        String result = "";
        try{
            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put("phoneNumber", getPara("phoneNumber"));
            hm.put("smsType", 9);
            hm.put("empCode", getPara("empCode"));//REST_HOST_PREFIX
            result = HttpUtil.syncGetParameterMap( REST_HOST_PREFIX+ "/sms/send",MediaType.JSON_UTF_8, hm);
        }
        catch(Exception e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @Title: getSendPassEncodeParams
     * @Description:TODO
     * @return String
     * @throws Exception
     */
    private String getSendPassEncodeParams() throws Exception{
        String value = "phone_no=" + getPara("phoneNo", "");// 四川移动手机号

        return new DESAS().encrypt(value);
    }

    /**
     * @Title: getValidVerifyCodeResult
     * @Description:获取请求验证验证码接口的结果
     * @return String
     */
    private String getValidVerifyCodeResult(){
        String result = "";
        try{
            String phoneNo = getPara("phoneNo", "");// 四川移动手机号
            String smsPwd = getPara("verifyCode");// 验证码
            HashMap<String, Object> value = new HashMap<>();
            value.put("phoneNumber",phoneNo);
            value.put("smsCode",smsPwd);//REST_HOST_PREFIX
            value.put("smsType",9);
            value.put("empCode",getPara("empCode", ""));
            result = HttpUtil.syncGetParameterMap( REST_HOST_PREFIX+ "/sms/validate",MediaType.JSON_UTF_8,value);
        }
        catch(Exception e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

    public void verifySms(){
        renderText(getValidVerifyCodeResult());
    }

    /**
     * @Title: getValidPassEncodeParams
     * @Description:TODO
     * @return String
     * @throws Exception
     */
    private String getValidPassEncodeParams() throws Exception{
        String phoneNo = getPara("phoneNo", "");// 四川移动手机号
        String smsPwd = getPara("verifyCode");// 验证码
        String value = "phone_no=" + phoneNo + "|smsPwd=" + smsPwd;

        return new DESAS().encrypt(value);
    }

    /**
     * @Title: getCustRealChkResult
     * @Description:获取请求验证实名认证接口的结果
     * @return String
     */
    private String getCustRealChkResult(){
        String result = "";
        try{
            // // String encodeParams = encodeParams(getCustRealChkParams());
            // String encodeParams = getCustRealChkEncodeParams();
            // logger.info("encodeParams = " + encodeParams);
            // HashMap<String, Object> hm = new HashMap<String, Object>();
            // // JSONObject o = new JSONObject(encodeParams);
            // // hm.put(H5ApiConstant.CmccKey.RAWSTR,
            // // o.get(H5ApiConstant.CmccKey.RAWSTR));
            // hm.put(H5ApiConstant.CmccKey.RAWSTR, encodeParams);
            //
            // result = HttpUtil.getHttpByPost(CMCC_HOST_PREFIX +
            // Constant.Url.CUST_REAL_CHK, hm);

            String phoneNo = getPara("phoneNo", "");

            JSONObject phone = new JSONObject();
            phone.put("PHONE_NO", phoneNo);

            JSONObject body = new JSONObject();
            body.put("BODY", phone);

            result = HttpUtil.syncPostJsonBody(REST_HOST_PREFIX + Constant.RestUrl.SQCHKCUSTREAL, MediaType.JSON_UTF_8,
                                               body.toString(), 30000);
        }
        catch(Exception e){
            e.printStackTrace();
        }

        return result;
    }

    /**
     * @Title: getCustRealChkEncodeParams
     * @Description:请求参数本地编码
     * @return String
     * @throws Exception
     */
    private String getCustRealChkEncodeParams() throws Exception{
        String phoneNo = getPara("phoneNo", "");
        String groupId = getPara("groupId", "");
        String loginNo = getPara("empCode", "");
        String value = "phone_no=" + phoneNo + "|group_id=" + groupId + "|login_no=" + loginNo;

        return new DESAS().encrypt(value);
    }

    /**
     * @param preAccept：移动接口返回的订单流水号
     * @Title: saveOrderToLacal
     * @Description:保存订单到本地数据库
     * @return boolean
     */
    private boolean saveOrderToLocal(long preAccept){
        ServiceReservation model = new ServiceReservation();
        if(preAccept != 0){// 仅保存订单需要的字段

            String memberPhone = getMemberPhone();

            model.set("manager_id", getPara("buildaddresId", null))// 资管ID
                    .set("channel_code", getPara("channelCode", ""))// 渠道编码
                    .set("order_id", preAccept)// 本地生成的订单流水号
                    .set("install_area", getPara("standAddress"))// 安装小区
                    .set("member_phone", memberPhone)// 成员手机号,多个电话号码保存到一个字段，用逗号隔开
                    .set("cust_sign", getPara("custSign", ""))// 客户签名
                    .set("province_card_no", getPara("custIDCard"));// 身份证号码
        }

        Broadband bd = Broadband.dao.getBroadbandInfoById(getParaToInt("broadbandId", 0));
        if(bd == null){
            return false;
        }

        // 保存订单和反馈信息都需要的字段
        Date create_date = new Date();// 创建时间
        model.set("appid", getParaToInt("appid", 100000056))// 目前写死
                .set("area", getPara("area", ""))// 区县
                .set("city", getPara("city", "成都"))// 城市，默认成都
                .set("install_address", getPara("addressDetail", ""))// 地址，.net版只有保存订单的时候才保存，保存反馈信息时没有保存
                .set("reward", 0.00)// 必填字段，不能为空，.net版只有保存订单的时候才保存，保存反馈信息时没有保存
                .set("create_date", create_date)// 创建时间
                .set("customer_name", getPara("customerName", ""))// 客户姓名
                .set("expected_install_time", getPreTime(getPara("preTime")))// 期望安装时间
                .set("feed_back", getPara("feedback", null))// 反馈内容
                .set("first_install_cost", getPara("firstInstallCost", "0.00"))// 初装费
                .set("is_pay", getParaToInt("isPay", 0))// 是否支付,0表示未支付，1表示已支付
                .set("broadband_id", getParaToInt("broadbandId", null))// 宽带预约ID
                .set("other_contact_phone", getPara("secondPhone"))// 其他联系电话
                .set("reservation_state", getParaToInt("reservation_state", 1))// 预约状态:1待审核,2审核通过,3审核不通过,4结单
                .set("sale_type", getParaToInt("saleType", 1))// 1.直销通原生App,2.直销通分享页面,3.微店，暂未使用
                .set("service_type", getParaToInt("serviceType", 2))// 服务类型:
                                                                    // 0贴膜预约,1维修预约,2宽带预约,3业务预约
                .set("org_id", getParaToInt("storeId", null))// 店铺ID，目前无店铺，传入的是机构ID
                .set("telephone", getPara("phoneNo", ""))// 客户电话
                .set("user_id", getParaToInt("userId", null))// 店员ID
                .set("gender", getParaToInt("gender", 0))// 客户性别 0先生 1女士
                .set("bd_name", bd.getStr("bd_name"))// 宽带资费名称
                .set("bd_code", bd.getStr("bd_code"))// 宽带资费代码
                .set("bd_summary", bd.getStr("bd_summary"))// 宽带资费简介
                .set("bd_creator_org_name", bd.getStr("bd_creator_org_name"));// 宽带资费发布人机构名称

        return model.save();
    }

    /**
     * @Title: getMemberPhone
     * @Description:封装成员电话号码
     * @return String
     */
    private String getMemberPhone(){
        String memberPhone1 = getPara("memberPhone1", "");
        String memberPhone2 = getPara("memberPhone2", "");
        String memberPhone3 = getPara("memberPhone3", "");
        String memberPhone4 = getPara("memberPhone4", "");
        String memberPhone5 = getPara("memberPhone5", "");

        StringBuffer sb = new StringBuffer();

        if(StrKit.notBlank(memberPhone1)){
            sb.append(memberPhone1);
            if(StrKit.notBlank(memberPhone2)){
                sb.append(",");
            } else{
                if(StrKit.notBlank(memberPhone3)){
                    sb.append(",");
                } else{
                    if(StrKit.notBlank(memberPhone4)){
                        sb.append(",");
                    } else{
                        if(StrKit.notBlank(memberPhone5)){
                            sb.append(",");
                        }
                    }
                }
            }
        }

        if(StrKit.notBlank(memberPhone2)){
            sb.append(memberPhone2);
            if(StrKit.notBlank(memberPhone3)){
                sb.append(",");
            } else{
                if(StrKit.notBlank(memberPhone4)){
                    sb.append(",");
                } else{
                    if(StrKit.notBlank(memberPhone5)){
                        sb.append(",");
                    }
                }
            }
        }

        if(StrKit.notBlank(memberPhone3)){
            sb.append(memberPhone3);
            if(StrKit.notBlank(memberPhone4)){
                sb.append(",");
            } else{
                if(StrKit.notBlank(memberPhone5)){
                    sb.append(",");
                }
            }
        }

        if(StrKit.notBlank(memberPhone4)){
            sb.append(memberPhone4);
            if(StrKit.notBlank(memberPhone5)){
                sb.append(",");
            }
        }

        if(StrKit.notBlank(memberPhone5)){
            sb.append(memberPhone5);
        }

        return sb.toString();
    }

    /**
     * @param preAccept
     * @Title: getSaveOrderResult
     * @Description:获取保存宽带预约订单到移动接口的结果
     * @return String
     */
    private String getSaveOrderResult(long preAccept){
        String result = "";
        try{
            // String encodeParams = encodeParams(getOrderParams(preAccept));
            String encodeParams = getOrderEncodeParams(preAccept);
            logger.info("encodeParams = " + encodeParams);
            HashMap<String, Object> hm = new HashMap<String, Object>();
            // JSONObject o = new JSONObject(encodeParams);
            // hm.put(H5ApiConstant.CmccKey.RAWSTR,
            // o.get(H5ApiConstant.CmccKey.RAWSTR));
            hm.put(H5ApiConstant.CmccKey.RAWSTR, encodeParams);

            result = HttpUtil.getHttpByPost(CMCC_HOST_PREFIX + Constant.Url.SAVE_BD_ORDER, hm);// 同大市场宽带预约是同一个接口
        }
        catch(Exception e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

    /**
     * @Title: getOrderEncodeParams
     * @Description:TODO
     * @param preAccept
     * @return String
     * @throws Exception
     */
    private String getOrderEncodeParams(long preAccept) throws Exception{
        // 根据店员ID获取店员信息
        MemberOrg member = MemberOrg.dao.getMemberOrgById(getParaToInt("userId"));
        String recruitPhone = "";// 发展人号码，此为APP中的店员号码
        String recruitName = "";// 发展人姓名，此为APP中的店员姓名
        if(member != null){
            recruitPhone = member.getStr("mobile");
            recruitName = member.getStr("name");
        }

        // 生成办理流水
        // String preAccept = getPreAccept();// 办理流水
        // 18位流水号：时间戳+4位随机码,yyyyMMddHHmmss
        // System.out.println("preAccept = " + preAccept);

        String idCard = getPara("custIDCard");// 用户的身份证号
        String standAddress = getPara("standAddress");// 小区地址
        // 去掉大括号{}
        String addressId = getAddressId(getPara("buildaddresId"));
        // System.out.println("addressId = " + addressId);

        String contactPhone = getPara("phoneNo");// 联系人手机号
        String contactName = getPara("customerName");
        String custGender = "0".equals(getPara("gender")) ? "男士" : "女士";
        String prodPrcid = getPara("prodPrcid");// 资费代码
        String secondPhone = getPara("secondPhone");
        String accessType = getPara("accessType");
        // 组装预约时间
        String preTime = getPreTime(getPara("preTime"));// 用户选择的预约安装时间,格式为yyyymmddhh24miss
        // System.out.println("preTime = " + preTime);

        String loginNo = getPara("empCode");// 工号
        String districtName = getPara("districtName");// 区县名称
        String netAttr = getPara("netAttr");// 网络归属
        String memberPhone1 = getPara("memberPhone1", "");
        String memberPhone2 = getPara("memberPhone2", "");
        String memberPhone3 = getPara("memberPhone3", "");
        String memberPhone4 = getPara("memberPhone4", "");
        String memberPhone5 = getPara("memberPhone5", "");
        String bak1 = getPara("cityCodeId", "");// 地市代码
        String bak2 = getPara("bdName");// 资费名称，此为选择的资费名称。如：优家保底送138（测试）
        String externAddress = getPara("addressDetail", "");// 详细地址
        String regionValue = getPara("regionValue", "");// 区县编码

        // add in 2016.5.23
        // String areaCode = getPara("areaCode", "");// 小区编号
        // 去掉大括号{}
        String areaCode = getAddressId(getPara("areaCode"));
        String areaName = getPara("areaName", "");// 小区地址

        if(StrKit.isBlank(accessType) || StrKit.isBlank(addressId) || StrKit.isBlank(netAttr)
                || StrKit.isBlank(areaCode) || StrKit.isBlank(areaName)){
            logger.error("accessType or buildaddresId or netAttr or areaCode or areaName!!!!");
        }

        String value = "pre_accept=" + preAccept + "|id_iccid=" + idCard + "|stand_address=" + standAddress
                + "|AddressId=" + addressId + "|contact_phone=" + contactPhone + "|contact_name=" + contactName
                + "|cust_gender=" + custGender + "|prod_prcid=" + prodPrcid + "|second_phone=" + secondPhone
                + "|access_type=" + accessType + "|pre_time=" + preTime + "|login_no=" + loginNo + "|member_phone1="
                + memberPhone1 + "|member_phone2=" + memberPhone2 + "|member_phone3=" + memberPhone3 + "|member_phone4="
                + memberPhone4 + "|member_phone5=" + memberPhone5 + "|NetAttr=" + netAttr + "|district_name="
                + districtName + "|bak1=" + bak1 + "|bak2=" + bak2 + "|extern_address=" + externAddress
                + "|recruit_phone=" + recruitPhone + "|recruit_name=" + recruitName + "|region_value=" + regionValue
                + "|AreaCode=" + areaCode + "|AreaName=" + areaName;

        logger.debug("params = " + value);

        return new DESAS().encrypt(value);
    }

    /**
     * @Title: getPreTime
     * @Description:用户选择的预约安装时间 格式为yyyymmddhh24miss
     * @param
     * @return String
     * @throws ParseException
     */
    private String getPreTime(String preTime){
        try{
            // System.out.println("preTime = " + preTime);
            if(StrKit.notBlank(preTime)){
                Calendar c = Calendar.getInstance();
                SimpleDateFormat sdfFrm = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdfTo = new SimpleDateFormat("yyyyMMdd");
                SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");

                c.setTime(sdfFrm.parse(preTime));

                preTime = sdfTo.format(c.getTime()) + sdf.format(new Date());
            }
        }
        catch(ParseException e){
            e.printStackTrace();
        }

        return preTime;
    }

    /**
     * @Title: getAddressId
     * @Description:去掉大括号{}
     * @param
     * @return String
     */
    private String getAddressId(String addressId){
        // System.out.println("addressId = " + addressId);
        if(StrKit.notBlank(addressId)){
            addressId = addressId.substring(1, addressId.length() - 1);
        }

        return addressId;
    }

    /**
     * @Title: getPreAccept
     * @Description:生成办理流水,18位流水号：时间戳+4位随机码,yyyyMMddHHmmss
     * @return String
     */
    private String getPreAccept(){
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String preAccept = sf.format(new Date()) + getRandomNumber(4);

        return preAccept;
    }

    /**
     * @Title: getRandomNumber
     * @Description:生成随机数
     * @return String
     */
    private String getRandomNumber(int count){
        StringBuffer sb = new StringBuffer();
        String str = "0123456789";
        Random r = new Random();
        for(int i = 0; i < count; i++){
            int num = r.nextInt(str.length());
            sb.append(str.charAt(num));
            str = str.replace(str.charAt(num) + "", "");
        }
        return sb.toString();
    }

    /**
     * @Title: encodeParams
     * @Description:移动参数编码接口
     * @param hm
     * @return String
     * @throws Exception
     */
    private String encodeParams(HashMap<String, Object> hm) throws Exception{
        return HttpUtil.getHttpByPost(CMCC_HOST_PREFIX + Constant.Url.ENCODE_URL, hm);
    }

    /**
     * 保存测试
     * 
     * @Title: saveOrderLocalTest
     * @Description:TODO void
     */
    // public void saveOrderLocalTest(){
    // long preAccept = Long.parseLong(getPreAccept());
    // if(saveOrderToLocal(preAccept)){
    // logger.error("saveOrderLocal success!!");
    // } else{
    // logger.error("saveOrderLocal failed!!");
    // }
    // }

    /**
     * 更新测试
     * 
     * @Title: updateOrderLocalTest
     * @Description:TODO void
     */
    // public void updateOrderLocalTest(){
    // String bossNo = getPara("boss_no");
    // String orderId = getPara("order_id");
    // if(ServiceReservation.dao.updateGovBdOrder(Long.parseLong(bossNo),
    // Long.parseLong(orderId))){
    // renderText("update local boss_no success!!!！");
    // } else{
    // renderText("update local boss_no failed!!!！");
    // }
    // }
    /**
     * 商务动力宽带预约返回数据解析测试
     * 
     * @Title: parseResultTest
     * @Description:TODO void
     */
    // public void parseResultTest(){
    // long orderId = getParaToLong("order_id");
    // // test success
    // // String saveOrderResult =
    // //
    // "{\"ROOT\":{\"RETURN_CODE\":0,\"RETURN_MSG\":\"ok!\",\"USER_MSG\":\"处理成功!\",\"DETAIL_MSG\":\"OK!\",\"PROMPT_MSG\":\"\",\"OUT_DATA\":{\"PRE_ACCEPT\":201607061133202130}}}";
    // // test fail
    // String saveOrderResult =
    // "{\"ROOT\":{\"RETURN_CODE\":302012899,\"RETURN_MSG\":\"数据库错误，请联系系统管理员！ERRID:35321920\",\"USER_MSG\":\"数据库错误，请联系系统管理员！\",\"DETAIL_MSG\":\"DBERRof
    // sBroadPreChg, 3 errid:1467771920\",\"PROMPT_MSG\":\"\"}}";

    // String saveOrderResult =
    // "{\"resCode\":\"0000000\",\"resMsg\":\"ok!\",\"detailMsg\":\"OK!\",\"outData\":{\"PRE_ACCEPT\":201607081119502786}}";

    // String saveOrderResult = null;
    // JSONObject o = null;
    // JSONObject objResult = new JSONObject();
    //
    // if(StrKit.notBlank(saveOrderResult))
    //
    // {
    // o = new JSONObject(saveOrderResult);
    // if(H5ApiConstant.CmccResultCode.SUCCESS_CODE.equals(o.getString(H5ApiConstant.CmccKey.RESCODE))){
    // // 5.更新本地订单boss_no
    // if(ServiceReservation.dao.updateGovBdOrder(
    // o.getJSONObject(H5ApiConstant.CmccKey.OUTDATA)
    // .getLong(H5ApiConstant.CmccKey.PRE_ACCEPT),
    // orderId)){
    // objResult.put(H5ApiConstant.CmccKey.RESCODE,
    // o.getString(H5ApiConstant.CmccKey.RESCODE));
    // } else{
    // logger.error("update local boss_no failed!!!！");
    // objResult.put(H5ApiConstant.CmccKey.RESCODE,
    // H5ApiConstant.ResultCode.EXCEPTION_CODE);
    // objResult.put(H5ApiConstant.CmccKey.RESMSG,
    // H5ApiConstant.Msg.SERVER_EXCEPTION);
    // }
    //
    // } else{
    // logger.error("save to DPR failed!!!！");
    // objResult.put(H5ApiConstant.CmccKey.RESCODE,
    // o.getString(H5ApiConstant.CmccKey.RESCODE));
    // objResult.put(H5ApiConstant.CmccKey.RESMSG,
    // o.getString(H5ApiConstant.CmccKey.RESMSG));
    // }
    //
    // } else
    //
    // {
    // logger.error("save to DPR exception!!!！");
    // objResult.put(H5ApiConstant.CmccKey.RESCODE,
    // H5ApiConstant.ResultCode.EXCEPTION_CODE);
    // objResult.put(H5ApiConstant.CmccKey.RESMSG,
    // H5ApiConstant.Msg.SAVE_BROADBAND_DPR_EXCEPTION);
    //
    // // result = objResult.toString();
    // }
    //
    // renderJson(objResult.toString());
    // }

    public void getBroadPortNum(){
        String result = sQBroadPortNum();

        renderJson(result);
    }

    /**
     * @Title: getCustRealChkResult
     * @Description:获取请求验证实名认证接口的结果
     * @return String
     */
    private String sQBroadPortNum(){
        String result = "";
        try{
            String encodeParams = getsQBroadPortNumEncodeParams();
            logger.info("encodeParams = " + encodeParams);
            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put(H5ApiConstant.CmccKey.RAWSTR, encodeParams);

            result = HttpUtil.getHttpByPost(CMCC_HOST_PREFIX + Constant.Url.sQBroadPortNum, hm);
        }
        catch(Exception e){
            e.printStackTrace();
        }

        return result;
    }

    /**
     * @Title: getCustRealChkEncodeParams
     * @Description:请求参数本地编码
     * @return String
     * @throws Exception
     */
    private String getsQBroadPortNumEncodeParams() throws Exception{
        String standard_address = getPara("standard_address", "");
        String group_id = getPara("group_id", "");
        String value = "standard_address=" + standard_address + "|group_id=" + group_id;

        return new DESAS().encrypt(value);
    }
}
